<template>
    <div class="wrapper">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
        
        <!-- 内容卡片 -->
        <el-card class="box-card">
            <!-- 添加角色 -->
            <template>
                <el-row>
                    <el-button type="primary" @click="addRoles.dialogSwitch = true">添加角色</el-button>
                </el-row>
                <el-dialog
                    title="添加角色"
                    :visible.sync="addRoles.dialogSwitch"
                    width="30%">

                    <el-form :model="addRoles.rolesFrom" :rules="addRoles.rules" ref='addUserRole' label-width="100px" class="demo-ruleForm">
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="addRoles.rolesFrom.name"></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述" prop="desc">
                            <el-input v-model="addRoles.rolesFrom.desc"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="addRoles.dialogSwitch = false">取 消</el-button>
                        <el-button type="primary" @click="addRoles.dialogSwitch = false;addUserRoleCheck()">确 定</el-button>
                    </span>
                </el-dialog>
            </template>

            <!-- 表格 -->
            <el-table
                :data="rolesData"
                style="width: 100%"
                border>
                <el-table-column type="expand">
                    <template v-slot='scope'>
                        <el-row class="rolesRow"
                            v-for="item1 in scope.row.children"
                            :key='item1.id'
                        >
                            <!-- 一级标题 -->
                            <el-col class="item1">
                                <el-tag type="danger">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级标题 -->
                            <el-col class='item2'>
                                <el-row v-for="item2 in item1.children" :key="item2.id">
                                    <el-col class="success">
                                        <el-tag  type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col class="warning"  v-for="item3 in item2.children" :key='item3.id'>
                                        <el-tag  type="warning">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                            
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column
                    label="序号"
                    type="index"
                    width="80">
                </el-table-column>
                <el-table-column
                    label="角色名称"
                    prop="roleName">
                </el-table-column>
                <el-table-column
                    label="角色描述"
                    prop="roleDesc">
                </el-table-column>
                <el-table-column
                    label="操作"
                    prop="desc"
                    width="300">
                    <template v-slot='scope'>
                        <el-button type="primary" size='mini' class="el-icon-edit" @click="modifyRole.dialogVisible = true; modifEditRolsData(scope.row)"> 编辑</el-button>
                        <el-button type="danger" size='mini' class="el-icon-delete" @click="deleteRole(scope.row.id)"> 删除</el-button>
                        <el-button type="warning" size='mini' class="el-icon-setting" @click="assignRoles(scope.row)"> 分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!-- 编辑角色对话框 -->
            <el-dialog
                title="编辑角色"
                :visible.sync="modifyRole.dialogVisible"
                width="30%">
                <el-form :model="modifyRole" :rules="addRoles.rules" ref='editRole' label-width="100px">
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="modifyRole.name"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="desc">
                        <el-input v-model="modifyRole.desc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="modifyRole.dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="modifyRole.dialogVisible = false; updateEditRolesData()">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配权限对话框 -->
            <el-dialog
                title="分配权限"
                :visible.sync="assignRolesData.rolesDialogVisible"
                width="35%"
            >
                <!-- 角色信息tree控件 -->
                <el-tree
                    :data="assignRolesData.data"
                    show-checkbox
                    node-key="id"
                    default-expand-all
                    :props="assignRolesData.defaultProps"
                    ref="tree">
                </el-tree>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="assignRolesData.rolesDialogVisible = false;">取 消</el-button>
                    <el-button type="primary" @click="assignRolesData.rolesDialogVisible = false;roleAuthorization()">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Roles",
        data() {
            return {
                // 添加角色
                addRoles: {
                    dialogSwitch: false,
                    rolesFrom: {
                        name: '',
                        desc: ''
                    },
                    rules: {
                        name: [
                            { required: true, message: '请输入角色名称', trigger: 'blur' }
                        ],
                        desc: [
                            { required: true, message: '请输入角色描述', trigger: 'blur' }
                        ]
                    }
                },
                // 角色数据
                rolesData: [],
                // 编辑角色
                modifyRole: {
                    id: '',
                    name: '',
                    desc: '',
                    dialogVisible: false,
                },
                assignRolesData: {
                    rolesDialogVisible: false,
                    // 所有权限数据
                    data: [],
                    // 指定tree控件的lable和children
                    defaultProps: {
                        children: 'children',
                        label: 'authName'
                    },
                    roleID: ''
                }
                
            }
        },
        created() {
            this.getRolesInfo();
            this.getJurisdictionList();
        },
        methods: {
            // 获取角色列表
            async getRolesInfo() {
                let {data: res} = await this.$http.get('/roles');
                if(res.meta.status !== 200) return this.$message.error('获取角色列表失败');
                this.rolesData = res.data;
            },
            // 获取所有权限列表
            getJurisdictionList() {
                this.$http.get('/rights/tree').then(res => {
                    this.assignRolesData.data =  res.data.data;
                })
            },
            // 校验和添加用户角色用户按钮
            addUserRoleCheck() {
                this.$refs.addUserRole.validate(async valid => {
                    if (valid) {
                        let {data: res} = await this.$http.post('/roles', {
                            roleName: this.addRoles.rolesFrom.name,
                            roleDesc: this.addRoles.rolesFrom.desc
                        });
                        if(res.meta.status !== 201) return this.$message.error('添加用户角色失败');
                        this.getRolesInfo();
                        this.$message.success('添加角色成功');
                        // 添加完成之后重置表单
                        this.$refs.addUserRole.resetFields();
                        
                    } else {
                        this.$message.error('添加角色信息有误，添加失败');
                        return false;
                    }
                });
            },

            // 修改编辑角色数据
            modifEditRolsData({id, roleDesc, roleName}) {
                this.modifyRole.id = id;
                this.modifyRole.name = roleName;
                this.modifyRole.desc = roleDesc;
            },
            async updateEditRolesData() {
                let {data: res} = await this.$http.put(`roles/${this.modifyRole.id}`, {
                    roleName: this.modifyRole.name,
                    roleDesc: this.modifyRole.desc
                })
                if(res.meta.status !== 200) return this.$message.error('修改用户角色失败');
                this.getRolesInfo();
                this.$message.success('修改角色成功');
            },
            // 删除角色
            deleteRole(id) {
                // console.log(id);
                this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let {data:res} = await this.$http.delete(`/roles/${id}`);
                    if(res.meta.status !== 200) return this.$message.error('删除角色失败');
                    this.getRolesInfo();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                })
            },
            // 分配权限
            assignRoles(rowInfo) {
                this.assignRolesData.id = rowInfo.id;
                this.assignRolesData.rolesDialogVisible = true;
                this.$nextTick(function() {
                    let arr = [];
                    function test(info) {
                        if(!info.children) return
                        info.children.forEach(value => {
                            arr.push(value.id);
                            test(value)
                        })
                    }
                    test(rowInfo);
                    this.$refs.tree.setCheckedKeys(arr);
                })
            },
            // 角色授权
            async roleAuthorization() {
                let rids = JSON.stringify(this.$refs.tree.getCheckedKeys());
                rids = rids.substring(1, rids.length-1);
                let {data: res} = await this.$http.post(`roles/${this.assignRolesData.id}/rights`, {
                    rids
                });
                if(res.meta.status !== 200) this.$message.error('权限修改失败');
                this.getRolesInfo();
                this.$message.success('权限更新成功');
            }
        }
    };
</script>

<style lang='less' scoped>
    .wrapper{
        width: 100%;
        height: 0px;
        padding: 10px 20px;
        box-sizing: border-box;
        .el-breadcrumb{
            padding-bottom: 10px;
        }
        .rolesRow{
            padding: 20px;
            display: flex;
            align-items: center;
            .item1{
                width: 170px;
                flex-shrink: 0;
                
            }
            .item2{
                flex-grow: 1;
                .el-row{
                    display: flex;
                    .success{
                        padding: 5px 0px;
                        display: flex;
                        align-items: center;
                        width: 100px;
                    }
                    .warning{
                        display: flex;
                        align-items: center;
                        width: 100px;
                    }
                }
            }
            
        }
    }
</style>




